local extension = Package:new("tea_ex_b")
extension.extensionName = "wild_collection"
Fk:loadTranslationTable{
  ["tea_ex_b"] = "茶水闲设二",
}
local U = require "packages/utility/utility"
local Est = require "packages/wild_collection/utility"

local caohong = General(extension, "tea__caohong", "wei", 4)
local zaobing = fk.CreateTriggerSkill{
  name = "tea_zaobing",
  anim_type = "offensive",
  events = {fk.TurnEnd},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player.room.current then
      if target ~= player and not target.dead then
        local room = player.room
        local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
          local use = e.data[1]
          return table.contains(TargetGroup:getRealTargets(use.tos), player.id) and use.card.type == Card.TypeTrick
        end, Player.HistoryTurn)
        return U.canUseCardTo(room, player, target, Fk:cloneCard("slash"), false, false) and #events > 0
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, self.name, "offensive")
		player:broadcastSkillInvoke(self.name, table.random({1, 2}))
    local current = room.current
    local card = Fk:cloneCard("slash")
    local use = {
      from = player.id,
      tos = {{current.id}},
      card = card,
      extraUse = true,
      extra_data = {is_zaobing = {player.id, current.id}}
    }
    room:useCard(use)
  end,
  refresh_events = {fk.CardUseFinished, fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    if event == fk.CardUseFinished then
      if data.card and player == target then
        if data.card.trueName == "slash" then
          if (data.extra_data or {}).is_zaobing then 
            return not table.contains((data.extra_data or {}).zaobing_damage or {}, data.extra_data.is_zaobing[2])
          end
        end
      end
    else
      if target == player then
        local room = player.room
        local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
        local events = {}
        if turn_event then
          room.logic:getEventsByRule(GameEvent.UseCard, 10, function (e)
            local use = e.data[1]
            if use.card == data.card and (use.extra_data or {}).is_zaobing then
              table.insert(events, use)
            end
          end, turn_event.id)
        end
        if #events > 0 then
          local use = events[1]
          self.cost_data = use
          return (use.extra_data or {}).is_zaobing
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      local from = room:getPlayerById(data.extra_data.is_zaobing[1])
      local to = room:getPlayerById(data.extra_data.is_zaobing[2])
      if room:askForSkillInvoke(to, self.name, nil, "#tea_zaobing-invoke:"..from.id) then
        room:notifySkillInvoked(player, self.name, "negative")
        player:broadcastSkillInvoke(self.name, 3)
        if #from:getCardIds("he") <= 2 then
          from:throwAllCards("he")
        else
          local cids = room:askForCardsChosen(to, from, 2, 2, "he", self.name, "#tea_zaobing-choose")
          room:throwCard(cids, self.name, from, to)
        end
      end
    else
      local extra = self.cost_data.extra_data
      if not extra.zaobing_damage then
        extra.zaobing_damage = {}
      end
      table.insert(extra.zaobing_damage, player.id)
    end
  end,
}
local yuanbo = fk.CreateTriggerSkill{
  name = "tea_yuanbo",
  anim_type = "defensive",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and data.from ~= player.id and data.card then
      if data.card.trueName == "slash" and player:inMyAttackRange(target) then
        return #Est.getCanBeDiscardedCards(player) > 0
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cids = room:askForDiscard(target, 1, 2, true, self.name, false, ".", "#tea_yuanbo-choose", true)
    if #cids > 0 then
      room:throwCard(cids, self.name, target, target)
      if not target.dead then
        target:drawCards(#cids, self.name)
      end
      if table.find(cids, function(id)
        local c = Fk:getCardById(id)
        return c.type == Card.TypeEquip
      end) then
        table.insertIfNeed(data.nullifiedTargets, target.id)
        if data.from then
          local from = room:getPlayerById(data.from)
          local card = Fk:cloneCard("duel")
          if not from.dead and U.canUseCardTo(room, from, player, card, false, false) then
            local use = {
              from = data.from,
              tos = {{player.id}},
              card = card,
              extraUse = true,
            }
            room:useCard(use)
          end
        end
      end
    end
  end,
}

caohong:addSkill(zaobing)
caohong:addSkill(yuanbo)
Fk:loadTranslationTable{
  ["tea__caohong"] = "曹洪",
  ["#tea__caohong"] = "潼关逞功",
  ["designer:tea__caohong"] = "孤豹",
  ["cv:tea__caohong"] = "茶社",
  ["illustrator:tea__caohong"] = "彭宇",
  ["tea_zaobing"] = "躁兵",
  [":tea_zaobing"] = "当你成为过锦囊牌目标的回合结束时，你可视为对当前回合角色使用一张无距离限制的【杀】。若此【杀】未对其造成伤害，其可弃置你两张牌。",
  ["#tea_zaobing-invoke"] = "你可以弃置 %src 两张牌",
  ["#tea_zaobing-choose"] = "选择两张牌弃置",
  ["tea_yuanbo"] = "援搏",
  [":tea_yuanbo"] = "当一名其他角色使用【杀】指定你攻击范围的角色为目标后，你可以令目标角色选择弃置至多两张牌并摸等量张牌，若其因此弃置了装备牌，则此【杀】对其无效，且此【杀】使用者视为对你使用一张【决斗】。",
  ["#tea_yuanbo-choose"] = "躁兵：你须至多弃置两张牌，然后摸等量牌，若其中有装备牌，此【杀】对你无效",

  ["$tea_zaobing1"] = "无畏无惧走四方，一往无前气势昂！",
  ["$tea_zaobing2"] = "马儿反复樵夫之后，何敢辱我曹氏宗门？",
  ["$tea_zaobing3"] = "（弃牌）躁而不乱，此乃兵法之道",
  ["$tea_yuanbo1"] = "酣宴绝缨效唐狡，岐山猎马报秦公。",
  ["$tea_yuanbo2"] = "马震西凉援明主，枪搏神威斗狂狮！",
  ["~tea__caohong"] = "急援虽至，躁进之祸难避……",
}

local yingyang = General(extension, "tea__yingyang", "wei", 3)
local getNeededNumbers = function(room)
  local arr = {}
  for _, p in ipairs(room.alive_players) do
    for _, id in ipairs(p:getCardIds("ej")) do
      table.insertIfNeed(arr, Fk:getCardById(id).number)
    end
  end
  local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
  numbers = table.filter(numbers, function(num)
    return not table.contains(arr, num)
  end)
  return numbers
end
local pianpian = fk.CreateViewAsSkill{
  name = "tea_pianpian",
  nim_type = "special",
  pattern = ".|.|.|.|.|basic",
  mute = true,
  prompt = function()
    local laizi = table.concat(getNeededNumbers(Fk:currentRoom()), ",")
    return "#tea_pianpian-prompt:::" .. laizi
  end,
  interaction = function()
    local all_names = U.getAllCardNames("b")
    local names = U.getViewAsCardNames(Self, "tea_pianpian", all_names, Self:getCardIds("h"))
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      return true
    elseif #selected == 1 then
      local laizi = getNeededNumbers(Fk:currentRoom())
      if Fk:getCardById(selected[1]):getMark("@@juejue_mark-inhand") > 0 then
        if Fk:getCardById(to_select):getMark("@@juejue_mark-inhand") > 0 then
          return table.find(laizi, function(num)
            return table.contains(laizi, num + 1) or table.contains(laizi, num - 1)
          end)
        else
          local num = Fk:getCardById(to_select).number
          return table.contains(laizi, num + 1) or table.contains(laizi, num - 1)
        end
      else
        if Fk:getCardById(to_select):getMark("@@juejue_mark-inhand") > 0 then
          local num = Fk:getCardById(selected[1]).number
          return table.contains(laizi, num + 1) or table.contains(laizi, num - 1)
        else
          return math.abs(Fk:getCardById(to_select).number - Fk:getCardById(selected[1]).number) == 1
        end
      end
    else
      return false
    end
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 2 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    local card1 = Fk:getCardById(use.card.subcards[1])
    local card2 = Fk:getCardById(use.card.subcards[2])
    local num1 = 0
    local num2 = 0
    room:notifySkillInvoked(player, self.name, "special")
    player:broadcastSkillInvoke(self.name, table.random({1, 2}))
    local laizi = getNeededNumbers(room)
    if card1:getMark("@@juejue_mark-inhand") > 0 then
      if card2:getMark("@@juejue_mark-inhand") > 0 then
        if card1.number ~= 13 then
          num1 = card1.number
          num2 = card1.number + 1
        else
          num1 = 13
          num2 = 12
        end
      else
        num2 = card2.number
        local nums = table.filter(laizi, function(n)
          return n == card2.number + 1 or n == card2.number - 1
        end)
        if #nums > 0 then
          num1 = nums[1]
        else
          num1 = 0
        end
      end
    else
      if card2:getMark("@@juejue_mark-inhand") > 0 then
        num1 = card1.number
        local nums = table.filter(laizi, function(n)
          return n == card1.number + 1 or n == card1.number - 1
        end)
        if #nums > 1 then
          num2 = nums[2]
        elseif #nums == 1 then
          num2 = nums[1]
        else
          num2 = 0
        end
      else
        num1 = card1.number
        num2 = card2.number
      end
    end
      
    local name = use.card.trueName
    if #player:getTableMark("@tea_pianpian_record") > 0 then
      if name ~= player:getTableMark("@tea_pianpian_record")[3] then
        --player:broadcastSkillInvoke(self.name, 3)
        player:drawCards(1, self.name)
      end
      local num3 = player:getTableMark("@tea_pianpian_record")[1]
      local num4 = player:getTableMark("@tea_pianpian_record")[2]

      if math.abs(num1 + num2 - num3 -num4) == 4 and player:isWounded() then
        --player:broadcastSkillInvoke(self.name, 4)
        player.room:recover{
          who = player,
          num = 1,
          skillName = self.name
        }
      end
    end
    player.room:setPlayerMark(player, "@tea_pianpian_record", {num1, num2, name})
  end,
  enabled_at_play = function(self, player)
    return true
  end,
  enabled_at_response = function(self, player, response)
    return not response
  end,
}
local juejue = fk.CreateTriggerSkill{
  name = "tea_juejue",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:loseHp(player, 1, self.name)
    if not player.dead then
      local cid = player:drawCards(1, self.name)
      room:setCardMark(Fk:getCardById(cid[1]), "@@juejue_mark-inhand", 1)
    end
  end,
}
local juejue_visible = fk.CreateVisibilitySkill{
  name = "#tea_juejue_visible",
  frequency = Skill.Compulsory,
  card_visible = function(self, player, card)
    if card:getMark("@@juejue_mark-inhand") > 0 and
      Fk:currentRoom():getCardArea(card) == Card.PlayerHand then
      return true
    end
  end
}
juejue:addRelatedSkill(juejue_visible)
yingyang:addSkill(pianpian)
yingyang:addSkill(juejue)
Fk:loadTranslationTable{
  ["tea__yingyang"] = "应玚",
  ["#tea__yingyang"] = "悲骥愁霖",
  ["designer:tea__yingyang"] = "cc",
  ["cv:tea__yingyang"] = "茶社",
  ["illustrator:tea__yingyang"] = "啪啪三国",
  ["tea_pianpian"] = "篇翩",
  [":tea_pianpian"] = "你可以将两张点数相邻的牌当任意基本牌使用；若转化牌名与上次不同，你摸一张牌；若转化底牌与上次仍构成相邻点数，你回复1点体力。",
  ["@tea_pianpian_record"] = "篇翩",
  ["#tea_pianpian-prompt"] = "场上缺少的点数： %arg （默认小点在前，大点在后）",
  ["tea_juejue"] = "珏决",
  [":tea_juejue"] = "锁定技，结束阶段，你失去 1 点体力，摸一张牌并始终明置之，此牌点数视为场上没有的任意点数直至你失去此牌。",
  ["@@juejue_mark-inhand"] = "珏决",

  ["$tea_pianpian1"] = "衔积石之重险兮，披山麓而溢浮。",
  ["$tea_pianpian2"] = "涉津洛之阪泉兮，播九道乎中州。",
  ["$tea_pianpian3"] = "（摸牌）翩然扶摇起，点墨化星辰。",
  ["$tea_pianpian4"] = "（回复）穆穆众君子，好合同欢康。",
  ["$tea_juejue1"] = "美玉碎尽金光在，残篇续得华章来。",
  ["$tea_juejue2"] = "病榻珏决，墨香犹存。",
  ["~tea__yingyang"] = "胸中千言未述，所志皆不遂。",
}

--王平
local wangping = General(extension, "tea__wangping", "shu", 4)
local feijun = fk.CreateTriggerSkill{
  name = "tea_feijun",
  anim_type = "drawcard",
  events = {fk.EventPhaseEnd},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if player.dead then return end
      return (player:getMark("tea_feijun_record") == 0 and player.phase == Player.Finish)
      or (player:getMark("tea_feijun_record") == player.phase)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local phases = {"准备阶段", "判定阶段", "摸牌阶段", "出牌阶段", "弃牌阶段", "结束阶段"}
    room:notifySkillInvoked(player, self.name, "drawcard")
    player:broadcastSkillInvoke(self.name, player.phase + 1)
    player:drawCards(3, self.name)
    if not player.dead then
      local cards_num = 0
      local num = #player:getCardIds(Player.Hand) - player.maxHp
      num = math.max(num, 0)
      if num > 0 then
        cards_num = #room:askForDiscard(player, num, num, false, self.name, false, nil, "#tea_feijun-ask:::"..tostring(num)) or 0
      end
      if cards_num < player.hp and not player.dead then
        room:notifySkillInvoked(player, self.name, "special")
        player:broadcastSkillInvoke(self.name, table.random({1, 2}))
        local choice = room:askForChoice(player, phases, self.name, "#tea_feijun-choose")
        room:setPlayerMark(player, "tea_feijun_record", table.indexOf(phases, choice) + 1)
        room:setPlayerMark(player, "@tea_feijun_shown", choice)
      end
    end
  end,
  refresh_events = {fk.GamePrepared},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@tea_feijun_shown", "结束阶段")
  end,
}
wangping:addSkill(feijun)
Fk:loadTranslationTable{
  ["tea__wangping"] = "王平",
  ["#tea__wangping"] = "兵谋致用",
  ["designer:tea__wangping"] = "菖蒲",
  ["cv:tea__wangping"] = "茶社",
  ["illustrator:tea__wangping"] = "Yanbai",
  ["tea_feijun"] = "飞军",
  [":tea_feijun"] = "结束阶段结束时，你可以摸三张牌并将手牌数弃置体力上限。"..
  "若以此法弃置的牌数小于你的体力值，你调整此技能的发动阶段。",
  ["@tea_feijun_shown"] = "飞军",
  ["#tea_feijun-ask"] = "飞军：你须弃置 %arg 张手牌",
  ["#tea_feijun-choose"] = "飞军：选择调整此技能发动阶段",

  ["$tea_feijun1"] = "（变更时）时移势易，飞军因变制宜。",
  ["$tea_feijun2"] = "（变更时）龙跃九天，飞军顺势而变。",
  ["$tea_feijun3"] = "（准备）牙门初立，裨将扬威。",
  ["$tea_feijun4"] = "（判定）统筹五部，调度有方。",
  ["$tea_feijun5"] = "（摸牌）整理军备，枕戈待战。",
  ["$tea_feijun6"] = "（出牌）全军列阵，准备冲锋！",
  ["$tea_feijun7"] = "（弃牌）整军若此，方能致远。",
  ["$tea_feijun8"] = "（结束）坚守城阙，来日再攻！",
  ["~tea__wangping"] = "汉中云渺飞军志，北伐征 途未竟时……",
}

local wangchong = General(extension, "tea__wangchong", "shu", 3)
local hongzi = fk.CreateViewAsSkill{
  name = "tea_hongcui",
  anim_type = "special",
  pattern = ".|.|.|.|.|trick",
  prompt = "#tea_hongcui-prompt",
  interaction = function()
    local all_names = U.getAllCardNames("t")
    local names = U.getViewAsCardNames(Self, "tea_hongcui", all_names, Self:getCardIds("h"))
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return true
  end,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    local name_len = Fk:translate(card.trueName, "zh_CN"):len()
    local selected_len = 0
    for _, id in ipairs(cards) do
      local n = Fk:translate(Fk:getCardById(id).trueName, "zh_CN"):len()
      selected_len = selected_len + n
    end
    if selected_len ~= name_len then return end
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  before_use = function(self, player, use)
    if #(use.card.subcards or {}) >= 2 then
      player:drawCards(1, self.name)
    end
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
}
local zaide = fk.CreateActiveSkill{
  name = "tea_zaide",
  anim_type = "drawcard",
  min_card_num = 1,
  card_filter = function (self, to_select, selected)
    if #selected == 0 then
      return true
    elseif #selected == 1 then
      local c1 = Fk:getCardById(selected[1])
      local c2 = Fk:getCardById(to_select)
      return c1.number == c2.number or c1.suit == c2.suit or c1.type == c2.type
    else
      local c1 = Fk:getCardById(selected[1])
      local c2 = Fk:getCardById(selected[2])
      local c = Fk:getCardById(to_select)
      if c1.number == c2.number then
        return c.number == c1.number
      elseif c1.suit == c2.suit then
        return c.suit == c2.suit
      elseif c1.type == c2.type then
        return c.type == c1.type
      end
    end
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:recastCard(effect.cards, player, self.name)
    local targets = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, #effect.cards, "#tea_zaide-choose:::"..tostring(#effect.cards), self.name)
    if #targets > 0 then
      room:sortPlayersByAction(targets)
      for _, id in ipairs(targets) do 
        room:getPlayerById(id):drawCards(1, self.name)
      end
    end
  end,
}
wangchong:addSkill(hongzi)
wangchong:addSkill(zaide)
Fk:loadTranslationTable{
  ["tea__wangchong"] = "王崇",
  ["#tea__wangchong"] = "尚书贞士",
  ["designer:tea__wangchong"] = "梁清渤",
  ["cv:tea__wangchong"] = "茶社",
  ["illustrator:tea__wangchong"] = "凝聚永恒",
  ["tea_hongcui"] = "弘粹",
  [":tea_hongcui"] = "每回合限一次，你可以将任意张牌当一张牌名字数为你以此法使用牌的牌名字数和的普通锦囊牌使用。若你以此法至少使用了两张牌，则你摸一张牌。",
  ["#tea_hongcui-prompt"] = "弘粹：你可以将几张牌转化成一张普通锦囊牌",
  ["tea_zaide"] = "载德",
  [":tea_zaide"] = "出牌阶段限一次，你可以重铸任意张花色/点数/类型相同的牌，然后你可以令至多等量名其他角色各摸一张牌。",
  ["#tea_zaide-choose"] = "你可以选择至多 %arg 名其他角色，令这些角色摸一张牌",

  ["$tea_hongcui1"] = "弘粹之技，集史成篇。",
  ["$tea_hongcui2"] = "史海拾贝，碎玉重圆。",
  ["$tea_zaide1"] = "宽仁待人，德行载物。",
  ["$tea_zaide2"] = "会友以德，共沐恩泽。",
  ["$tea_zaide3"] = "以德相交心无骛，重铸旧篇情谊长。",
  ["~tea__wangchong"] = "史册未完，笔锋已断……",
}
local weiyao = General(extension, "tea__weiyao", "wu", 3)
local juzheng = fk.CreateTriggerSkill{
  name = "tea_juzheng",
  anim_type = "control",
  events = {fk.CardUsing, fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardUsing then
      return data.card.is_damage_card and player:hasSkill(self) and player ~= target
    else
      return player:hasSkill(self) and player:getMark("@@tea_juzheng_used-turn") > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.CardUsing then
      local room = player.room
      local ids = table.filter(player:getCardIds("he"), function(id)
        return Fk:getCardById(id).type == data.card.type and Fk:getCardById(id).trueName ~= data.card.trueName
      end)
      local c = room:askForCard(player, 1, 1, true, self.name, true, tostring(Exppattern{ id = ids }), "#tea_juzheng-choose")
      if #c == 1 then
        self.cost_data = c
        return true
      end
    else
      if #player.room.logic:getActualDamageEvents(1, Util.TrueFunc, Player.HistoryTurn) == 0 then
        self.cost_data = player:usedSkillTimes(self.name, Player.HistoryTurn)
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing then
      room:moveCards{
        ids = self.cost_data,
        from = player.id,
        toArea = Card.DrawPile,
        moveReason = fk.ReasonPut,
        skillName = self.name,
        proposer = player.id,
        moveVisible = true,
      }
      room:setPlayerMark(player, "@@tea_juzheng_used-turn", 1)
      data.tos = {}
    else
      local num = self.cost_data
      local cids = room:askForDiscard(player, num, num, true, self.name, false, ".", "#tea_juzheng-discard:::" .. tostring(num))
      if not player.dead and #cids > 0 then
        player:drawCards(#cids, self.name)
      end
    end
  end,
}
local sheniang = fk.CreateFilterSkill{
  name = "tea_sheniang",
  frequency = Skill.Compulsory,
  mute = true,
  card_filter = function(self, card, player)
    if not player:hasSkill(self) then return end
    if player.hp > player:getMark("round_count") then
      return table.contains(player:getCardIds("h"), card.id) and card.trueName == "analeptic"
    elseif player.hp < player:getMark("round_count") then
      return table.contains(player:getCardIds("h"), card.id) and card.trueName == "peach"
    end
  end,
  view_as = function(self, card, player)
    if player.hp > player:getMark("round_count") then
      local c = Fk:cloneCard("peach", card.suit, card.number)
      c.skillName = self.name
      return c
    elseif player.hp < player:getMark("round_count") then 
      local c = Fk:cloneCard("analeptic", card.suit, card.number)
      c.skillName = self.name
      return c
    end
  end,
}
local sheniang_trigger = fk.CreateTriggerSkill{
  name = "#tea_sheniang_trigger",
  refresh_events = {fk.RoundStart,fk.PreCardUse},
  can_refresh = function(self, event, target, player, data)
    if event == fk.RoundStart then
      return player:hasSkill("tea_sheniang", true)
    else
      return target == player and table.contains(data.card.skillNames or {}, sheniang.name) 
    end
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.RoundStart then
      player.room:setPlayerMark(player, "round_count", player.room:getTag("RoundCount"))
    else
      player.room:notifySkillInvoked(player, sheniang.name, "special")
      if data.card.trueName == "peach" then
        player:broadcastSkillInvoke(sheniang.name, 1)
      else
        player:broadcastSkillInvoke(sheniang.name, 2)
      end
    end
  end,
}

sheniang:addRelatedSkill(sheniang_trigger)
weiyao:addSkill(juzheng)
weiyao:addSkill(sheniang)
Fk:loadTranslationTable{
  ["tea__weiyao"] = "韦曜",
  ["#tea__weiyao"] = "所言不讳",
  ["designer:tea__weiyao"] = "とわこ",
  ["cv:tea__weiyao"] = "茶社",
  ["illustrator:tea__weiyao"] = "啪啪三国",
  ["tea_juzheng"] = "据正",
  [":tea_juzheng"] = "其他角色使用伤害牌时，你可以将一张与此牌类型相同牌名不同的牌置于牌堆顶，然后取消此次用牌。此回合结束时，若本回合没有角色受到伤害，你弃置 X 张牌并摸等量牌（X为本回合此技能发动次数）。",
  ["@@tea_juzheng_used-turn"] = "据正",
  ["#tea_juzheng-choose"] = "据正：你可以将一张与使用牌类型相同但牌名不同的牌置于牌堆顶，然后取消之",
  ["#tea_juzheng-discard"] = "据正：你须弃置 %arg 张牌，然后摸等量牌",
  ["tea_sheniang"] = "蔎酿",
  [":tea_sheniang"] = "锁定技，若你的体力值大于/小于当前游戏轮数，你手牌中的【酒】/【桃】视为【桃】/【酒】。",

  ["$tea_juzheng1"] = "笔锋所指，邪妄皆退。",
  ["$tea_juzheng2"] = "据史以实谬自散，正本清源道为先。",
  ["$tea_sheniang1"] = "（酒转化桃）酒入愁肠，化作茶香。",
  ["$tea_sheniang2"] = "（桃转化酒）茶代酒香清心志，心如水静淡泊明。",
  ["~tea__weiyao"] = "不降志于白刃、不曲笔以求存，此千秋正义！",
}
local chengpu = General(extension, "tea__chengpu", "wu", 4)
local fenpan = fk.CreateActiveSkill{
  name = "tea_fenpan",
  anim_type = "offensive",
  min_target_num = 1,
  card_filter = Util.FalseFunc,
  mute = true,
  target_filter = function(self, to_select, selected)
    return #selected == 0 or Fk:currentRoom():getPlayerById(selected[1]).hp == Fk:currentRoom():getPlayerById(to_select).hp
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:notifySkillInvoked(player, self.name, "offensive")
	  player:broadcastSkillInvoke(self.name, table.random({1, 2}))
    local targets = effect.tos
    room:sortPlayersByAction(targets)
    local card = Fk:cloneCard("fire_attack")
    local use = {
      from = player.id,
      tos = table.map(targets, function(id)
        return {id}
      end),
      card = card,
      extraUse = true,
      extra_data = {tea_fenpan = true},
    }
    room:useCard(use)
    if table.find(targets, function(id)
      return room:getPlayerById(id).dead
    end) and not player.dead then
      room:notifySkillInvoked(player, self.name, "negative")
	    player:broadcastSkillInvoke(self.name, 3)
      local cids = room:askForDiscard(player, 2, 2, true, self.name, true, ".", "#tea_fenpan-discard")
      if #cids < 2 then
        room:loseHp(player, 1, self.name)
      end
    end
  end,
}
local dangkou = fk.CreateTriggerSkill{
  name = "tea_dangkou",
  anim_type = "drawcard",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and data.card.is_damage_card and data.card.type == Card.TypeTrick
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:showCards(player:getCardIds("h"))
    local suits = {}
    for _, id in ipairs(player:getCardIds("h")) do
      table.insertIfNeed(suits, Fk:getCardById(id).suit)
    end
    local num = 4 - #suits
    if not data.extra_data then
      data.extra_data = {tea_dangkou = num}
    elseif type(data.extra_data) == "table" then
      data.extra_data.tea_dangkou = num
    end
  end,
  refresh_events = {fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(self, true) and data.extra_data then
      return data.extra_data.tea_dangkou and data.damageDealt
    end
  end,
  on_refresh = function(self, event, target, player, data)
    player:drawCards(data.extra_data.tea_dangkou, self.name)
  end,
}
chengpu:addSkill(fenpan)
chengpu:addSkill(dangkou)
Fk:loadTranslationTable{
  ["tea__chengpu"] = "程普",
  ["#tea__chengpu"] = "疠火焚叛",
  ["designer:tea__chengpu"] = "菖蒲",
  ["cv:tea__chengpu"] = "茶社",
  ["illustrator:tea__chengpu"] = "Zero",
  ["tea_fenpan"] = "焚叛",
  [":tea_fenpan"] = "出牌阶段限一次，你可以视为对任意名手牌数相同的角色使用一张【火攻】，若有目标角色因此死亡，你失去 1 点体力或弃两张牌。",
  ["#tea_fenpan-discard"] = "焚叛：你须弃置两张牌，或点取消并失去1点体力",
  ["tea_dangkou"] = "荡寇",
  [":tea_dangkou"] = "当你使用伤害类锦囊牌指定目标后，你可展示所有手牌。此牌结算后，若对目标造成伤害，你摸 X 张牌（X 为你展示牌中缺少的花色数）。",

  ["$tea_fenpan1"] = "叛军数百，尽入炼狱火海！",
  ["$tea_fenpan2"] = "焚天烈火，一丘之貉皆灭！",
  ["$tea_fenpan3"] = "（负面）心焚同烬，孽火无情！",
  ["$tea_dangkou1"] = "统军胸纳千军策，应变自通万变局。",
  ["$tea_dangkou2"] = "三朝虎臣兵无影，四海荡平寇无踪。",
  ["~tea__chengpu"] = "火海焚尽叛军影，犹存烈焰问苍穹……",
}
local zhengxuan = General(extension, "tea__zhengxuan", "qun", 3)
local zhujing = fk.CreateTriggerSkill{
  name = "tea_zhujing",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Start
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local suc, dat = room:askForUseActiveSkill(player, "tea_zhujing_active", "#tea_zhujing-invoke", true)
    if suc then
      self.cost_data = dat
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local dat = self.cost_data
    local card = Fk:cloneCard(dat.interaction)
    card:addSubcards(dat.cards)
    card.skillName = self.name
    local use = {
      from = player.id,
      tos = table.map(dat.targets, function(id)
        return {id}
      end),
      card = card,
    }
    room:useCard(use)
    if not player.dead then
      room:setPlayerMark(player, "@tea_zhujing_mark", {Fk:getCardById(dat.cards[1]).trueName, card.trueName})
      for _, p in ipairs(room.alive_players) do
        room:setPlayerMark(p, "tea_zhujing_trans", {Fk:getCardById(dat.cards[1]).trueName, card.trueName})
        if not p:hasSkill(Fk.skills["tea_zhujing_other&"]) then
          room:handleAddLoseSkills(p, "tea_zhujing_other&", nil, true)
        end
      end
    end
  end,
  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self.name, true, true) and player == target
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@tea_zhujing_mark", 0)
    for _, p in ipairs(room.alive_players) do
      room:setPlayerMark(p, "tea_zhujing_trans", 0)
      if p:hasSkill(Fk.skills["tea_zhujing_other&"], true) then
        room:handleAddLoseSkills(p, "-tea_zhujing_other&", nil, true)
      end
    end
  end,
}
local zhujing_check = fk.CreateTriggerSkill{
  name = "#tea_zhujing_check",
  mute = true,

  refresh_events = {fk.EventAcquireSkill, fk.EventLoseSkill, fk.BuryVictim, fk.AfterPropertyChange},
  can_refresh = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return data == self
    elseif event == fk.BuryVictim then
      return target:hasSkill(self, true, true)
    elseif event == fk.AfterPropertyChange then
      return target == player
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local need = table.find(room.alive_players, function (p)
      return p:hasSkill(self, true)
    end) and table.find(room.alive_players, function (p)
      return p:getMark("@tea_zhujing_mark") ~= 0
    end)
    if need and not player:hasSkill("tea_zhujing_other&", true, true) then
      room:handleAddLoseSkills(player, "tea_zhujing_other&", nil, true, true)
    elseif not need and player:hasSkill("tea_zhujing_other&", true, true) then
      room:handleAddLoseSkills(player, "-tea_zhujing_other&", nil, true, true)
    end
  end,
}
local zhujing_active = fk.CreateViewAsSkill{
  name = "tea_zhujing_active",
  mute = true,
  interaction = function()
    local all_names = U.getAllCardNames("t")
    all_names = table.filter(all_names, function(n)
      return not Fk:cloneCard(n).is_damage_card
    end)
    local names = U.getViewAsCardNames(Self, "tea_zhujing_active", all_names, Self:getCardIds("h"))
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeBasic
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 1 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
}
local zhujing_other = fk.CreateViewAsSkill{
  name = "tea_zhujing_other&",
  mute = true,
  interaction = function()
    local all_names = {Self:getTableMark("tea_zhujing_trans")[2]}
    local names = U.getViewAsCardNames(Self, "tea_zhujing_other&", all_names, Self:getCardIds("h"))
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == Self:getTableMark("tea_zhujing_trans")[1]
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 1 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
}
local zhuwo = fk.CreateTriggerSkill{
  name = "tea_zhuwo",
  anim_type = "special",
  frequency = Skill.Limited,
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player == target and player:usedSkillTimes(self.name, Player.HistoryGame) == 0 then
      local num = #U.getAllCardNames("b", true)
      return #player:getTableMark("@$tea_zhuwo_record") >= num
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cids = {}
    for i = 1, 6 do
      table.insert(cids, room.draw_pile[i])
    end
    player:showCards(cids)
    cids = table.filter(cids, function(id)
      return Fk:getCardById(id).type == Card.TypeBasic
    end)
    while #cids > 0 and not player.dead do
      cids = table.filter(cids, function(id)
        return room:getCardArea(id) == Card.DrawPile
      end)
      local suc, dat = room:askForUseActiveSkill(player, "tea_zhujing_zhuwo_active", "#tea_zhujing-invoke", true, {expand_pile = cids})
        if suc then
          local card = Fk:cloneCard(dat.interaction)
          card:addSubcards(dat.cards)
          card.skillName = self.name
          local use = {
            from = player.id,
            tos = table.map(dat.targets, function(id)
              return {id}
            end),
            card = card,
          }
          table.removeOne(cids, dat.cards[1])
          room:useCard(use)
        else
          break
        end
    end
  end,
  refresh_events = {fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    if not player:hasSkill(self, true) then return end
    local cids = {}
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if Fk:getCardById(info.cardId).type == Card.TypeBasic then
            table.insertIfNeed(cids, info.cardId)
          end
        end
      end
    end
    if #cids > 0 then
      self.cost_data = cids
      return true
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local cards = self.cost_data
    if player.dead then return end
    local mark = player:getTableMark("@$tea_zhuwo_record")
    for _, id in ipairs(cards) do
      if table.every(mark, function(c)
        return Fk:getCardById(c).trueName ~= Fk:getCardById(id).trueName
      end) then
        table.insert(mark, id)
      end
    end
    room:setPlayerMark(player, "@$tea_zhuwo_record", mark)
  end,
}
local zhujing_zhuwo_active = fk.CreateViewAsSkill{
  name = "tea_zhujing_zhuwo_active",
  mute = true,
  interaction = function()
    local all_names = U.getAllCardNames("t")
    all_names = table.filter(all_names, function(n)
      return not Fk:cloneCard(n).is_damage_card
    end)
    local names = U.getViewAsCardNames(Self, "tea_zhujing_active", all_names, Self:getCardIds("h"))
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeBasic and table.contains(self.expand_pile, to_select)
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 1 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
}
Fk:addSkill(zhujing_active)
Fk:addSkill(zhujing_other)
Fk:addSkill(zhujing_zhuwo_active)
zhujing:addRelatedSkill(zhujing_check)
zhengxuan:addSkill(zhujing)
zhengxuan:addSkill(zhuwo)
Fk:loadTranslationTable{
  ["tea__zhengxuan"] = "郑玄",
  ["#tea__zhengxuan"] = "椎琢诗礼",
  ["designer:tea__zhengxuan"] = "妙啊",
  ["cv:tea__zhengxuan"] = "茶社",
  ["illustrator:tea__zhengxuan"] = "monkey",
  ["tea_zhujing"] = "注经",
  [":tea_zhujing"] = "准备阶段，你可以将一张基本牌当一张非伤害类普通锦囊牌使用，直到你下回合开始，所有角色出牌阶段限一次，其可将一张此牌名的基本牌当一张此牌名的普通锦囊牌使用。",
  ["#tea_zhujing-invoke"] = "注经：你可以将一张基本牌当一张非伤害类普通锦囊牌使用",
  ["tea_zhujing_other&"] = "注经",
  [":tea_zhujing_other&"] = "出牌阶段限一次，你可以将一张已记录的基本牌当一张已记录的普通锦囊牌使用。",
  ["@tea_zhujing_mark"] = "注经",
  ["tea_zhujing_active"] = "注经",
  ["tea_zhuwo"] = "注我",
  [":tea_zhuwo"] = "限定技，回合结束时，若你本局游戏已失去过所有牌名的基本牌，你可以展示牌堆顶六张牌，然后依次用其中的基本牌发动“注经”。",
  ["@$tea_zhuwo_record"] = "注我",
  ["tea_zhujing_zhuwo_active"] = "注我",

  ["$tea_zhujing1"] = "文词婉转，言辞多变，当注而解其意。",
  ["$tea_zhujing2"] = "经纶浩渺，注此卷以述，盼天下共知。",
  ["$tea_zhuwo1"] = "六经注我学无尽，四海传经世不息。",
  ["$tea_zhuwo2"] = "君子知夫不全不粹，犹自锥刀隳太山。",
  ["~tea__zhengxuan"] = "经学已终，注疏难续……",
}
local zhangwen = General(extension, "tea__zhangwen", "qun", 4)
local countNumbers = function(cards)
  local n = 0 
  for _, id in ipairs(cards) do
    n = n + Fk:getCardById(id).number
  end
  return n
end
local weibing = fk.CreateTriggerSkill{
  name = "tea_weibing",
  anim_type = "drawcard",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and data.card.is_damage_card and data.firstTarget
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = U.getActualUseTargets(room, data, event)
    if #targets > 0 then
      room:sortPlayersByAction(targets)
      local cids = room:getNCards(3)
      room:moveCardTo(cids, Card.Processing, nil, fk.ReasonJustMove)
      for _, id in ipairs(cids) do
        room:setCardMark(Fk:getCardById(id), "@@tea_weibing_mark-phase", 1)
      end
      for _, id in ipairs(targets) do
        if #cids < 1 then break end
        local p = room:getPlayerById(id)
        local suc, dat = room:askForUseActiveSkill(p, "tea_weibing_ask_skill", "#tea_weibing-invoke:" .. player.id .. "::" ..
         tostring(countNumbers(cids)) .. ":" .. data.card:toLogString(), true, {hand_cards = p:getCardIds("h"), shown_cards = cids})
        if suc then
          local cards = dat.cards
          room:throwCard(cards, self.name, p, p)
          table.insertIfNeed(data.nullifiedTargets, p.id)
        else
          if #cids > 0 then
            local cid = room:askForCard(player, 1, 1, false, self.name, false, ".|.|.|^(hand,equip)", "#tea_weibing-choose", cids)
            if #cid == 1 then
              room:obtainCard(player, cid, true, fk.ReasonPrey)
              table.removeOne(cids, cid[1])
              for _, id in ipairs(cid) do
                room:setCardMark(Fk:getCardById(id), "@@tea_weibing_mark-phase", 0)
              end
            end
          end
        end
      end
      if #cids > 0 then
        room:moveCardTo(cids, Card.DiscardPile, nil, fk.ReasonJustMove, self.name)
        for _, id in ipairs(cids) do
          room:setCardMark(Fk:getCardById(id), "@@tea_weibing_mark-phase", 0)
        end
      end
    end
  end,
}
local weibing_ask = fk.CreateViewAsSkill{
  name = "tea_weibing_ask_skill",
  mute = true,
  card_filter = function(self, to_select, selected)
    return table.contains(self.hand_cards, to_select)
  end,
  target_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if countNumbers(cards) <= countNumbers(self.shown_cards) then return end
    local c = Fk:cloneCard("dilu")
    c.skillName = self.name
    return c
  end,
}
Fk:addSkill(weibing_ask)
local hanlv = fk.CreateTriggerSkill{
  name = "tea_hanlv",
  frequency = Skill.Compulsory,
  events = {fk.DamageInflicted, fk.CardUsing},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if target ~= player or not player:hasSkill(self) then return end
    if event == fk.DamageInflicted then
      return data.damage > 1 and player:getMark("tea_hanlv_mark") == 0
    else
      if data.card.is_damage_card then
        return #U.getActualUseTargets(player.room, data, event) == 1 and #player.room:getUseExtraTargets(data, false, false) > 0
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.DamageInflicted then
      player.room:notifySkillInvoked(player, self.name, "defensive")
		  player:broadcastSkillInvoke(self.name, 2)
      data.damage = 1
    else
      local room = player.room
      room:notifySkillInvoked(player, self.name, "defensive")
		  player:broadcastSkillInvoke(self.name, table.random({1, 2}))
      local targets = room:getUseExtraTargets(data, false, false)
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#tea_hanlv_choose:::" .. data.card:toLogString(), self.name, false)
      if #to == 1 then
        table.insert(data.tos, {to[1]})
        room:sendLog{ type = "#AddTargetsBySkill", from = player.id, to = {to[1]}, arg = self.name, arg2 = data.card:toLogString() }
      end
    end
  end,

  refresh_events = {fk.AfterDrawPileShuffle},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self.name, true)
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:notifySkillInvoked(player, self.name, "special")
		player:broadcastSkillInvoke(self.name, 1)
    player.room:setPlayerMark(player, "tea_hanlv_mark", 1)
  end,
}
zhangwen:addSkill(weibing)
zhangwen:addSkill(hanlv)
Fk:loadTranslationTable{
  ["tea__zhangwen"] = "张温",
  ["#tea__zhangwen"] = "汉道日衰",
  ["designer:tea__zhangwen"] = "妙啊",
  ["cv:tea__zhangwen"] = "茶社",
  ["illustrator:tea__zhangwen"] = "柏桦",
  ["tea_weibing"] = "威兵",
  [":tea_weibing"] = "你使用伤害类牌指定目标后，可以亮出牌堆顶三张牌，令目标角色依次选择一项：1.弃置点数和大于当前亮出牌点数和的任意张手牌，令此牌对其无效；2.令你获得一张亮出牌。",
  ["@@tea_weibing_mark-phase"] = "威兵亮出",
  ["#tea_weibing-invoke"] = "威兵：你可以弃置任意张点数和大于 %arg 的手牌并令此 %arg2 对你无效，或点击取消令 %src 获得一张亮出牌",
  ["#tea_weibing-choose"] = "威兵：获得一张亮出牌",
  ["tea_weibing_ask_skill"] = "威兵",
  ["tea_hanlv"] = "汉律",
  [":tea_hanlv"] = "锁定技，若牌堆未洗过牌，当你受到大于 1 点的伤害时，将伤害值改为 1 点；当你使用单目标伤害类牌时，多指定一名目标角色。",
  ["#tea_hanlv_choose"] = "汉律：你须为此 %arg 选择一个额外目标",

  ["$tea_weibing1"] = "谅尔等将寡兵微，安能抵敌王师？",
  ["$tea_weibing2"] = "威兵临境，弃甲或降，叛贼作何想？",
  ["$tea_hanlv1"] = "（洗牌时）皇天倾、后土颓，世将离乱兮汉祚衰。",
  ["$tea_hanlv2"] = "（减伤）汉律尚存，吾令如山。",
  ["$tea_hanlv3"] = "斩长鲸、驱龙虎，汉将横行破残贼。",
  ["$tea_hanlv4"] = "延大祚、庇蒸民，月明寰宇归炎汉。",
  ["~tea__zhangwen"] = "千里草青，知汉祚将终……",
}
local shibao = General(extension, "tea__shibao", "jin", 4)
local zuojing = fk.CreateViewAsSkill{
  name = "tea_zuojing",
  frequency = Skill.Limited,
  pattern = "nullification;.|.|.|.|.|basic",
  mute = true,
  interaction = function()
    local all_names = U.getAllCardNames("b")
    table.insert(all_names, "nullification")
    local names = U.getViewAsCardNames(Self, "tea_zuojing", all_names)
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return false
  end,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    room:notifySkillInvoked(player, self.name, "big")
    if use.card.type == Card.TypeBasic then
      player:broadcastSkillInvoke(self.name, 1)
    else
      player:broadcastSkillInvoke(self.name, 2)
    end
  end,
  after_use = function(self, player, use)
    local name = Fk:cloneCard(self.interaction.data).trueName
    player.room:setPlayerMark(player, "@zuojing_record", name)
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
}
local zuojing_refresh = fk.CreateTriggerSkill{
  name = "#tea_zuojing_refresh",
  refresh_events = {fk.CardUsing},
  can_refresh = function(self, event, target, player, data)
    if player == target and player:getMark("@zuojing_record") == data.card.trueName then
      local room = player.room
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
      local cards = {}
      room.logic:getEventsByRule(GameEvent.UseCard, 999, function(e)
        local use = e.data[1]
        if use.card.trueName == player:getMark("@zuojing_record") and use.from == player.id then
          table.insert(cards, use.card)
        end
        return false
      end, turn_event.id)
      return #cards == 1
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"tea_zuojing_refresh", "tea_zuojing_drawcards", "Cancel"}, self.name, "#tea_zuojing_choice")
    if choice == "tea_zuojing_refresh" then
      room:notifySkillInvoked(player, zuojing.name, "special")
		  player:broadcastSkillInvoke(zuojing.name, 4)
      player:setSkillUseHistory("tea_zuojing", 0, Player.HistoryGame)
      player.room:setPlayerMark(player, "@zuojing_record", 0)
    elseif choice == "tea_zuojing_drawcards" then
      room:notifySkillInvoked(player, zuojing.name, "drawcard")
		  player:broadcastSkillInvoke(zuojing.name, 3)
      local to = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#tea_zuojing_choose")
      if #to > 0 then
        room:getPlayerById(to[1]):drawCards(2, self.name)
      end
    end
  end,
}
local fenwu = fk.CreateTriggerSkill{
  name = "tea_fenwu",
  anim_type = "support",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      for _, move in ipairs(data) do
        if move.moveReason == fk.ReasonDiscard and move.from then
          local cids = {}
          for _, info in ipairs(move.moveInfo) do
            table.insertIfNeed(cids, info.cardId)
          end
          if #cids > 1 then
            self.cost_data = {
              from = move.from,
              cids = cids,
            }
            return not player.room:getPlayerById(move.from):isNude() and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.from)
    local cids = self.cost_data.cids
    local r_cards = {}
    for i = 1, 2 do
      if to:isNude() then break end
      local r_cid = room:askForCard(to, 1, 1, true, self.name, false, ".", "#tea_fenwu-choose")
      if #r_cid > 0 then
        table.insert(r_cards, r_cid[1])
        room:recastCard(r_cid, to, self.name)
      end
    end
    if #r_cards == 2 then
      if Fk:getCardById(r_cards[1]).color == Fk:getCardById(r_cards[2]).color then
        cids = table.filter(cids, function(id)
          return room:getCardArea(id) == Card.DiscardPile
        end)
        if #cids > 0 then
          local choose_cid = room:askForCard(to, 1, 1, false, self.name, true, ".|.|.|^(hand,equip)", "#tea_fenwu-obtain", cids)
          if #choose_cid > 0 then
            room:obtainCard(to, choose_cid, true, fk.ReasonPrey)
          end
        end
      end
    end
  end,
}
zuojing:addRelatedSkill(zuojing_refresh)
shibao:addSkill(zuojing)
shibao:addSkill(fenwu)
Fk:loadTranslationTable{
  ["tea__shibao"] = "石苞",
  ["#tea__shibao"] = "陵岩峻立",
  ["designer:tea__shibao"] = "梦貘",
  ["cv:tea__shibao"] = "茶社",
  ["illustrator:tea__shibao"] = "凡果",
  ["tea_zuojing"] = "佐靖",
  [":tea_zuojing"] = "限定技，你可以视为使用一张基本牌或【无懈可击】。此技能的状态为已发动时，你每回合首次使用与以此法使用的同名牌时，可以重置此技能或令一名角色摸两张牌。",
  ["@zuojing_record"] = "佐靖",
  ["#tea_zuojing_choice"] = "佐靖：选择一项",
  ["tea_zuojing_refresh"] = "复原“佐靖”",
  ["tea_zuojing_drawcards"] = "令一名角色摸两张牌",
  ["#tea_zuojing_choose"] = "选择一名角色，令其摸两张牌",
  ["tea_fenwu"] = "奋务",
  [":tea_fenwu"] = "每回合限一次，当一名角色弃置至少两张牌后，你可以令其依次重铸两张牌，若这两张牌颜色相同，其可以收回弃置牌中一张牌。",
  ["#tea_fenwu-choose"] = "奋务：选择一张牌重铸",
  ["#tea_fenwu-obtain"] = "奋务：选择一张牌获得",

  ["$tea_zuojing1"] = "（基本）佐靖辅国，一掷定音。",
  ["$tea_zuojing2"] = "（无懈）忠允清亮，才经世务。",
  ["$tea_zuojing3"] = "（摸牌）儒雅豁达志不懈，佐靖天下量无竭。",
  ["$tea_zuojing4"] = "（重置）文帝败于东关也，苞独全军而退。",
  ["$tea_fenwu1"] = "干用之绩，所历可纪。",
  ["$tea_fenwu2"] = "明智有量，奋务无疆。",
  ["~tea__shibao"] = "一朝失势，忠骨埋荒丘……",
}
local zuosi = General(extension, "tea__zuosi", "jin", 3)
local zhuanfu = fk.CreateActiveSkill{
  name = "tea_zhuanfu",
  anim_type = "special",
  card_num = 1,
  card_filter = function(self, to_select, selected)
    if #selected == 0 and Fk:getCardById(to_select):isCommonTrick() then
      local names = {}
      for _, c in ipairs(Self:getPile("tea_zhuanfu_record")) do
        table.insertIfNeed(names, Fk:getCardById(c).trueName)
      end
      return not table.contains(names, Fk:getCardById(to_select).trueName)
    end
  end,
  can_use = function(self, player)
    return true
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local cards = effect.cards
    player:addToPile("tea_zhuanfu_record", cards, true, self.name, player.id)
    room:setPlayerMark(player, "@tea_tengchao_num", 1)
  end,
}
local zhuanfu_trigger = fk.CreateTriggerSkill{
  name = "#tea_zhuanfu_trigger",
  anim_type = "special",
  events = {fk.GameStart},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, zhuanfu.name, "special")
		player:broadcastSkillInvoke(zhuanfu.name)
    local cids = {}
    for _, id in ipairs(room.draw_pile) do
      if Fk:getCardById(id):isCommonTrick() then
        table.insert(cids, id)
      end
    end
    if #cids > 0 then
      local cid = table.random(cids, 1)
      room:obtainCard(player, cid, false, fk.ReasonPrey)
    end
  end,
}
local tengchao = fk.CreateViewAsSkill{
  name = "tea_tengchao",
  anim_type = "special",
  pattern = ".|.|.|.|.|trick",
  prompt = "#tea_tengchao_other-active",
  interaction = function()
    local all_names = U.getAllCardNames("t")
    local names = U.getViewAsCardNames(Self, "tea_tengchao", all_names, Self:getCardIds("he"))
    local use_names = table.map(Self:getPile("tea_zhuanfu_record"), function(c)
      return Fk:getCardById(c).name
    end)
    names = table.filter(names, function(n)
      return table.contains(use_names, n)
    end)
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return true
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards <= Self:getMark("@tea_tengchao_num") then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    use.extra_data = {tengchao_use = true}
    room:setPlayerMark(player, "@tea_tengchao_num", #(use.card.subcards or {}))
  end,
  enabled_at_play = function(self, player)
    return player.phase ~= Player.NotActive and player:getMark("@tea_tengchao_num") > 0 and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and player.phase ~= Player.NotActive and player:getMark("@tea_tengchao_num") > 0 and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
}
local tengchao_trigger = fk.CreateTriggerSkill{
  name = "#tea_tengchao_trigger",
  mute = true,

  refresh_events = {fk.EventAcquireSkill, fk.EventLoseSkill, fk.BuryVictim, fk.AfterPropertyChange, fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return data == self
    elseif event == fk.BuryVictim then
      return target:hasSkill(self, true, true)
    elseif event == fk.AfterPropertyChange then
      return target == player
    else
      return player:hasSkill(tengchao) and (data.extra_data or {}).tengchao_use
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event ~= fk.CardUseFinished then
      local suc = table.find(room.alive_players, function (p)
        return p ~= player and p:hasSkill(self, true)
      end)
      if suc and not player:hasSkill("tea_tengchao&", true, true) then
        room:handleAddLoseSkills(player, "tea_tengchao&", nil, false, true)
      elseif not suc and player:hasSkill("tea_tengchao&", true, true) then
        room:handleAddLoseSkills(player, "-tea_tengchao&", nil, false, true)
      end
    else
      local cid = room:askForCard(player, 1, 1, false, tengchao.name, true, ".|.|.|^(hand,equip)", "#tea_tengchao_choose", data.card.subcards)
      if #cid == 1 then
        room:obtainCard(player, cid, true, fk.ReasonPrey)
      end
    end
  end,
}
local tengchao_other = fk.CreateViewAsSkill{
  name = "tea_tengchao&",
  anim_type = "special",
  pattern = ".|.|.|.|.|trick",
  prompt = "#tea_tengchao_other-active",
  mute = true,
  interaction = function()
    local all_names = U.getAllCardNames("t")
    local names = U.getViewAsCardNames(Self, "tea_tengchao", all_names, Self:getCardIds("he"))
    local source = table.filter(Fk:currentRoom().alive_players, function(p)
      return p:getMark("@tea_tengchao_num") > 0
    end)[1]
    local use_names = table.map(source:getPile("tea_zhuanfu_record"), function(c)
      return Fk:getCardById(c).name
    end)
    names = table.filter(names, function(n)
      return table.contains(use_names, n)
    end)
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return true
  end,
  view_as = function(self, cards)
    local source = table.filter(Fk:currentRoom().alive_players, function(p)
      return p:getMark("@tea_tengchao_num") > 0
    end)[1]
    if not self.interaction.data or #cards <= source:getMark("@tea_tengchao_num") then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    use.extra_data = {tengchao_use = true}
    local targets = table.filter(room.alive_players, function(p)
      return p:hasSkill(tengchao)
    end)
    if #targets > 0 then
      local target = targets[1]
      room:setPlayerMark(target, "@tea_tengchao_num", #(use.card.subcards or {}))
      room:notifySkillInvoked(player, tengchao.name, "special")
      target:broadcastSkillInvoke(tengchao.name)
    end
  end,
  enabled_at_play = function(self, player)
    local source = table.filter(Fk:currentRoom().alive_players, function(p)
      return p:getMark("@tea_tengchao_num") > 0
    end)
    return player.phase ~= Player.NotActive and #source > 0 and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  enabled_at_response = function(self, player, response)
    local source = table.filter(Fk:currentRoom().alive_players, function(p)
      return p:getMark("@tea_tengchao_num") > 0
    end)
    return not response and player.phase ~= Player.NotActive and #source > 0 and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
}
Fk:addSkill(tengchao_other)
zhuanfu:addRelatedSkill(zhuanfu_trigger)
tengchao:addRelatedSkill(tengchao_trigger)
zuosi:addSkill(zhuanfu)
zuosi:addSkill(tengchao)
Fk:loadTranslationTable{
  ["tea__zuosi"] = "左思",
  ["#tea__zuosi"] = "洛阳纸贵",
  ["designer:tea__zuosi"] = "杜预",
  ["cv:tea__zuosi"] = "茶社",
  ["illustrator:tea__zuosi"] = "啪啪三国",
  ["tea_zhuanfu"] = "撰赋",
  [":tea_zhuanfu"] = "游戏开始时，你从牌堆获得一张普通锦囊牌。每种牌名限一次，出牌阶段，你可以将一张普通锦囊牌置于武将牌上，称为“赋”，然后重置“誊钞”中 X 的值。",
  ["#tea_zhuanfu_trigger"] = "撰赋",
  ["tea_zhuanfu_record"] = "赋",
  ["tea_tengchao"] = "誊钞",
  [":tea_tengchao"] = "每名角色的回合限一次，其可以将至少 X+1 张牌当与任意一张“赋”牌名相同的牌使用（X 为以此法使用的上一张牌对应的实体牌数且至少为 1）。此牌结算后，你可以获得这些牌中的一张。",
  ["tea_tengchao&"] = "誊钞",
  [":tea_tengchao&"] = "你的回合限一次，你可以将至少 X+1 张牌当与任意一张“赋”牌名相同的牌使用（X 为以此法使用的上一张牌对应的实体牌数且至少为 1）。",
  ["@tea_tengchao_num"] = "誊钞",
  ["#tea_tengchao_other-active"] = "你可以将一些牌转化成一张普通锦囊牌",
  ["#tea_tengchao_choose"] = "誊钞：你可以获得其中一张牌",

  ["$tea_zhuanfu1"] = "挥毫泼墨，此赋当为传世之作。",
  ["$tea_zhuanfu2"] = "叙风俗人物，志山川草木。",
  ["$tea_tengchao1"] = "赋成三都名噪起，洛阳纸贵墨香浓。",
  ["$tea_tengchao2"] = "辞义瑰玮，良可贵也。",
  ["~tea__zuosi"] = "赋笔已折文思尽，洛阳纸绝竹筒空……",
}

return extension